<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!-- <el-form-item label="归属区域名称" prop="belongAreaName">
        <el-input v-model="queryParams.belongAreaName" placeholder="请输入归属区域名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="归属门店名称" prop="belongStoreName">
        <el-input v-model="queryParams.belongStoreName" placeholder="请输入归属门店名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="适用区域" prop="belongAreaName">
        <el-select clearable v-model="queryParams.belongAreaName" @change="changeRegion">
          <el-option v-for="(item, index) of region" :key="index" :label="item.value" :value="item.value">{{
            item.value
          }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="适用门店" prop="belongStoreName">
        <el-select clearable v-model="queryParams.belongStoreName" @change="handleQuery">
          <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.value">{{
            item.value
          }}</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="jobNumber">

        <el-input
          v-model="queryParams.jobNumber"
          placeholder="请输入门工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
        <!-- <el-input v-model="queryParams.jobNumber" placeholder="请输入工号" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">

        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />

      
        <!-- <el-input v-model="queryParams.name" placeholder="请输入员工姓名" clearable @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="时间" prop="name">
        <el-date-picker v-model="searchTime" type="daterange" align="right"  range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:master:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-for="(item, index) in btnData" :key="index">
        <el-button size="mini" @click="handleChange(item.number, index)"
          :class="activeIndex === index ? 'activeBtn' : 'btn'">{{ item.name }}</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="earningsList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="订单ID" align="center" :show-overflow-tooltip="true" prop="orderId" />
      <el-table-column label="归属区域" align="center" :show-overflow-tooltip="true" prop="belongAreaName" />
      <el-table-column label="归属门店" align="center" :show-overflow-tooltip="true" prop="belongStoreName" />
      <el-table-column label="员工姓名" align="center" :show-overflow-tooltip="true" prop="name" />
      <el-table-column label="工号" align="center" prop="jobNumber" />

      <el-table-column label="项目类型" align="center" prop="earningsType">

        <template slot-scope="scope">
          <span v-if="scope.row.earningsType==1">项目收益</span>
          <span v-if="scope.row.earningsType==2">附加商品收益</span>
          <span v-if="scope.row.earningsType==3">包间收益</span>
          <span v-if="scope.row.earningsType==4">会员卡收益</span>
          <span v-if="scope.row.earningsType==5">储值卡收益</span>
          <span v-if="scope.row.earningsType==6">退款收益</span>
        </template>
      </el-table-column>

      <el-table-column label="项目名称" align="center" prop="ortherName">
      </el-table-column>
      
      <el-table-column label="本次收益" align="center" prop="earnings">
        <template slot-scope="scope">
          {{ scope.row.earnings || "0.0" }}
        </template>
      </el-table-column>

      <el-table-column label="总收益" align="center" prop="techTotalEarning">
        <template slot-scope="scope">
          {{ scope.row.techTotalEarning || "0.0" }}
        </template>
      </el-table-column>

    
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:master:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getAllList" />

    <!-- 添加或修改技师收益对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="技师id" prop="technicianId">
          <el-input v-model="form.technicianId" placeholder="请输入技师id" />
        </el-form-item>
        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="form.jobNumber" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="归属门店id" prop="belongStoreId">
          <el-input v-model="form.belongStoreId" placeholder="请输入归属门店id" />
        </el-form-item>
        <el-form-item label="归属门店名称" prop="belongStoreName">
          <el-input v-model="form.belongStoreName" placeholder="请输入归属门店名称" />
        </el-form-item>
        <el-form-item label="归属区域id" prop="belongAreaId">
          <el-input v-model="form.belongAreaId" placeholder="请输入归属区域id" />
        </el-form-item>
        <el-form-item label="归属区域名称" prop="belongAreaName">
          <el-input v-model="form.belongAreaName" placeholder="请输入归属区域名称" />
        </el-form-item>
        <el-form-item label="月份" prop="monthTime">
          <el-input v-model="form.monthTime" placeholder="请输入月份" />
        </el-form-item>
        <el-form-item label="项目id" prop="ortherId">
          <el-input v-model="form.ortherId" placeholder="请输入项目id" />
        </el-form-item>
        <el-form-item label="项目名称" prop="ortherName">
          <el-input v-model="form.ortherName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="收益" prop="earnings">
          <el-input v-model="form.earnings" placeholder="请输入收益" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEarnings,
  getEarnings,
  delEarnings,
  addEarnings,
  updateEarnings,
  gettechnician,
} from "@/api/system/earnings";
import {
  listtechnician,
  listMemberRegion,
  listMemberStore,
} from "@/api/system/personnelMatters/technicianClock";

export default {
  name: "Earnings",
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '当月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              const now = new Date();
              // 设置当前月份的第一天（00:00:00）
              now.setDate(1);
              now.setHours(0, 0, 0, 0);
              start.setTime(start.getTime() - (start.getTime() - now.getTime()));
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '上月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              // 获取当前日期
              const now = new Date();
              // 获取上个月的第一天
              const firstDayOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
              // 获取上个月的最后一天
              const lastDayOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
              start.setTime(firstDayOfLastMonth.getTime());
              end.setTime(lastDayOfLastMonth.getTime());
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      region: [],
      store: [],
      // 遮罩层
      loading: true,
      number: "",
      activeIndex: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 技师收益表格数据
      earningsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        earningsType: null,
        technicianId: null,
        jobNumber: null,
        name: null,
        phoneNumber: null,
        belongStoreId: null,
        belongStoreName: null,
        belongAreaId: null,
        belongAreaName: null,
        monthTime: null,
        ortherId: null,
        ortherName: null,
        earnings: null,
      },
      searchTime: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      btnData: [
        {
          name: "全部收益",
        },
        {
          name: "项目收益",
          number: 1,
        },
        {
          name: "附加商品收益",
          number: 2,
        },
        {
          name: "包间收益",
          number: 3,
        },
        {
          name: "会员卡收益",
          number: 4,
        },
        {
          name: "储值卡收益",
          number: 5,
        },
        {
          name: "退款收益",
          number: 6,
        },
      ],
      btnForm: {
        1: "项目名称",
        2: "附加商品名称",
        3: "包间名称",
        4: "会员卡名称",
        5: "储值卡名称",
      },
      numberArr: [],
      nameArr: [],

    };
  },
  created() {
    this.getAllList();
    this.getNameNumber()
    this.listregion()
    listMemberStore().then((res) => {
      console.log(res, 333);
      this.store = res.data.map((rItem) => {
        return {
          key: rItem.id,
          value: rItem.storeName,
        };
      });
    });
  },
  methods: {
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      if (value) {
        this.handleQuery()
        const selectedOption = this.region.find((item) => item.value == value);
        if (!selectedOption) return
        const selectedKey = selectedOption.key;
        console.log(selectedKey, 'selectedKey');

        listMemberStore({ regionId: selectedKey }).then((res) => {
          console.log(res, 'res');

          this.store = res.data.map((rItem) => {
            return {
              key: rItem.id,
              value: rItem.storeName,
            };
          });
        });
      }

    },
    getAllList() {
      console.log(this.searchTime)
      let params = {
        ...this.queryParams,
        startTime: this.searchTime && this.searchTime.length > 0 && this.searchTime[0] || '',
        endTime: this.searchTime && this.searchTime.length > 0 && this.searchTime[1] || '',
      }
      gettechnician(params).then((response) => {
        this.earningsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取姓名工号
    getNameNumber() {
      this.nameArr = [],
        this.numberArr = []
      const queryParams = {
        pageNum: 1,
        pageSize: 999,
      }
      listtechnician(queryParams).then((response) => {
        const map = new Map();
        const newArr = response.rows.filter(v => !map.has(v.jobNumber) && map.set(v.jobNumber, v));
        newArr.map(el => {
          this.numberArr.push({
            label: el.jobNumber,
            value: el.jobNumber
          })
          this.nameArr.push({
            label: el.name,
            value: el.name
          })
        })
      });
    },
    handleChange(item, index) {
      this.activeIndex = index;
      console.log(item);
      if (item) {
        this.queryParams.earningsType = item;
        this.getAllList();
        // this.number = item;
      } else {
        this.queryParams.earningsType = null;
        // this.number = null;
        this.getAllList();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        technicianId: null,
        jobNumber: null,
        name: null,
        phoneNumber: null,
        belongStoreId: null,
        belongStoreName: null,
        belongAreaId: null,
        belongAreaName: null,
        monthTime: null,
        ortherId: null,
        ortherName: null,
        earningsType: null,
        earnings: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAllList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加技师收益";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEarnings(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改技师收益";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateEarnings(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getAllList();
            });
          } else {
            addEarnings(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getAllList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除技师收益编号为"' + ids + '"的数据项？')
        .then(function () {
          return delEarnings(ids);
        })
        .then(() => {
          this.queryParams.earningsType = null;
          this.getAllList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/earnings/export",
        {
          ...this.queryParams,
        },
        `earnings_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.activeBtn {
  border-radius: 13.34rpx;
  background: rgba(42, 130, 228, 1);
  color: rgba(255, 255, 255, 1);
}

.btn {
  border-radius: 13.34rpx;
  background: rgba(229, 229, 229, 1);
  color: rgba(128, 128, 128, 1);
}
</style>
